package com.yst.sqlbuilder;


import com.yst.lambda.TableFieldFunc;
import lombok.Getter;

import java.util.*;
import java.util.stream.Collectors;

public class SQLJoinCondition<S,R> implements ISQLExpression, IParentedSelect<S>{
    @Getter
    private final SQLJoin<S,R> sqlJoin;
    public SQLJoinCondition(SQLJoin<S,R> parentJoin) {
        this.sqlJoin=parentJoin;
    }

    private final List<IExpression> expressionList=new ArrayList<>();
    @SafeVarargs
    public final SQLJoinCondition<S,R> isRightNull(TableFieldFunc<R, ?>... fields){
        expressionList.addAll(Arrays.stream(fields).map(it->new SQLFieldIsNull<>(it)
                        .setTableAlias(sqlJoin)).collect(Collectors.toList()));
        return this;
    }
    @SafeVarargs
    public final SQLJoinCondition<S,R> isNull(TableFieldFunc<R, ?>... fields){
        return isRightNull(fields);
    }
    @SafeVarargs
    public final SQLJoinCondition<S,R> isRightNotNull(TableFieldFunc<R,?>...fields){
        expressionList.addAll(Arrays.stream(fields).map(it-> new SQLFieldIsNotNull<>(it)
                .setTableAlias(sqlJoin)).collect(Collectors.toList()));
        return this;
    }
    @SafeVarargs
    public final SQLJoinCondition<S,R> isNotNull(TableFieldFunc<R,?>...fields){
        return isRightNotNull(fields);
    }
    public SQLJoinCondition<S,R> equal(TableFieldFunc<S,?> fieldLeft, TableFieldFunc<R,?> fieldRight){
        expressionList.add(new SQLFieldCompareExp<S>(sqlJoin.getParentSelect(),fieldLeft).setValue(fieldRight));
        return this;
    }
    public SQLJoinCondition<S,R> equal(TableFieldFunc<R,?> fieldRight, Object value){
        expressionList.add(new SQLFieldCompareExp<>(sqlJoin,fieldRight).setValue(value).setSymbol(Symbol.EQ));
        return this;
    }
    public SQLJoinCondition<S,R> in(TableFieldFunc<R,?> field, Collection<?> values){
        expressionList.add(new SQLFieldIn<>(this.getSqlJoin(), field).setValues(values));
        return this;
    }
    public SQLJoinCondition<S,R> in(TableFieldFunc<R,?> field, Object...values){
        expressionList.add(new SQLFieldIn<>(this.getSqlJoin(), field).setValues(Arrays.asList(values)));
        return this;
    }
    public SQLJoinCondition<S,R> inSelect(TableFieldFunc<R,?> field, ISQLSelect subSelect){
        subSelect.setParentSelect(this.getSqlJoin().getParentSelect());
        expressionList.add(new SQLFieldIn<>(getSqlJoin(), field).setSelect(subSelect));
        return this;
    }
    @Override
    public String generateExpression(GenerateParam param) {
        return null;
    }
    @Override
    public SQLSelect<S> getParentSelect() {
        return sqlJoin.getParentSelect();
    }
    public SQLSelectCondition<S> getParent(){
        return sqlJoin.getParentSelect().getWhere();
    }
}
